import React, {Component} from 'react';
import {
    StatusBar, Dimensions,
    StyleSheet, Image,
    Text, TextInput, Platform,
    View, TouchableOpacity, Alert, AsyncStorage
} from 'react-native';
import {toJS} from 'mobx';
import {observer} from 'mobx-react/native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import Icon from 'react-native-vector-icons/FontAwesome';
import LinearGradient from 'react-native-linear-gradient';
import DeviceInfo from 'react-native-device-info';
import FormInput from './components/FormInput';
import FormStore from './store/FormStore';
import Indicator from '../../../components/Indicator';
import Tool from '../../../components/Tool';

@observer
export default class SignIn extends Component {
    static navigationOptions = {
        header: null
    };

    constructor(props) {
        super(props);
        this.form = new FormStore();
        this.state = {
            indicatorVisable: false
        };
        this._initFormData();
    }

    _initFormData() {
        AsyncStorage.multiGet([Tool.storageConst.userKey, Tool.storageConst.passwordKey], (error, results) => {
            if (results[0][1]) {
                try {
                    let user = JSON.parse(results[0][1]);
                    this.form.setValue('a4Code', user.a4Code);
                } catch (err) {

                }
            }
            if (results[1][1]) {
                try {
                    this.form.setValue('password', results[1][1]);
                    this.form.setValue('remember', true);
                } catch (err) {

                }
            }
        });
    }

    _handleSubmitLogin() {
        this._showIndicator();
        let signInForm = toJS(this.form);
        signInForm.appLoginLog = {
            loginAddress: '',
            appVersion: '1.3.5',
            deviceImei: DeviceInfo.getSerialNumber(),
            deviceModel: DeviceInfo.getModel(),
            deviceVendor: DeviceInfo.getBrand(),
            deviceUUID: DeviceInfo.getUniqueID(),
            networdInfo: DeviceInfo.getCarrier(),
            osLanguage: DeviceInfo.getDeviceLocale(),
            osVersion: DeviceInfo.getSystemVersion(),
            osName: DeviceInfo.getSystemName(),
            osVendor: DeviceInfo.getManufacturer(),
            launchLoaded: ''
        };
        let _this = this;
        Tool.fetchJson(Tool.appPath.mkst + 'login/inteLogin', JSON.stringify(signInForm), function (data) {
            if (data.state && data.code === 'NEED_VALICODE') {
                _this.form.setValue('showValicode', true);
                _this._hideIndicator();
                Alert.alert('提示', '验证码已发送至 ' + data.info + ' 请注意查收.');
            } else if (data.state && data.code === 'LOGIN_SUCCESS') {
                AsyncStorage.setItem(Tool.storageConst.userKey, JSON.stringify(data.info))
                if (_this.form.remember) {
                    AsyncStorage.setItem(Tool.storageConst.passwordKey, _this.form.password);
                } else {
                    AsyncStorage.removeItem(Tool.storageConst.passwordKey);
                }
                _this._hideIndicator();
                _this.props.navigation.replace('Gesture');
            } else {
                _this._hideIndicator();
                Alert.alert('提示', JSON.stringify(data));
            }
        }, function (error) {
            _this._hideIndicator();
        });
    }

    _handleRemember() {
        // this.setState(preState => { return {remember: !preState.remember}; });
        this.form.setValue('remember', !this.form.remember);
    }

    _showIndicator() {
        this.setState({indicatorVisable: true});
    }

    _hideIndicator() {
        this.setState({indicatorVisable: false});
    }

    render() {
        let {height, width} = Dimensions.get('window');
        return (
            <KeyboardAwareScrollView>
                <StatusBar backgroundColor="#FFFFFF" barStyle="dark-content"/>
                <View style={{height:height-StatusBar.currentHeight,backgroundColor:'#FFFFFF'}}>
                    <View style={{flex:1,alignItems: 'center'}}>
                        <LinearGradient colors={['#DCEEF3', '#5A81FB']}
                                        style={styles.bgCricle1}></LinearGradient>
                        <LinearGradient colors={['#7E9BFC', '#EFDDCE']}
                                        style={styles.bgCricle2}></LinearGradient>
                        <LinearGradient colors={['#E7EAF4', '#CBD6FC']}
                                        style={styles.bgCricle3}></LinearGradient>
                        <LinearGradient colors={['#7E9BFC', '#EFDDCE']}
                                        style={styles.bgCricle4}></LinearGradient>
                        <LinearGradient colors={['#E8F5F6', '#C0D0FA']}
                                        style={styles.bgCricle5}></LinearGradient>
                        <Image source={require('./../../../assets/base/login-icon.png')} style={styles.bgLogoImg}/>

                        <View style={{width:'100%',paddingHorizontal:50}}>
                            <FormInput titleCN="用户名"
                                       titleUS="USER NAME"
                                       titleSP="/"
                                       form={this.form}
                                       name='a4Code'/>
                            <FormInput titleCN="密码"
                                       titleUS="PASSWORD"
                                       titleSP="/"
                                       form={this.form}
                                       name='password'
                                       secureTextEntry/>
                            {this.form.showValicode ? (<FormInput titleCN="验证码"
                                                                  titleUS="VERIFICATION CODE"
                                                                  titleSP="/"
                                                                  keyboardType="numeric"
                                                                  form={this.form}
                                                                  name="valicode"
                                                                  onSendMarkEvent={() => this._handleSubmitLogin()}
                                                                  sendMark={true}/>) : null}
                            <View style={{flexDirection:'row',justifyContent:'space-between',marginTop:10}}>
                                <TouchableOpacity onPress={this._handleRemember.bind(this)}>
                                    <Text><Icon name={this.form.remember ? 'check-square-o' : 'square-o'} size={13}
                                                color="#00A0FF"/> 记住密码</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => Alert.alert('提示','请前往4A系统修改密码.')}>
                                    <Text>忘记密码?</Text>
                                </TouchableOpacity>
                            </View>
                            <LinearGradient colors={['#00A0FE', '#5580FD']} style={styles.submitBtn}>
                                <TouchableOpacity style={{paddingVertical:8,}}
                                                  disabled={!this.form.submitDisabled}
                                                  onPress={this._handleSubmitLogin.bind(this)}>
                                    <Text
                                        style={{color:this.form.submitDisabled ? '#FFFFFF':'#AAAAAA',textAlign:'center'}}>登  陆</Text>
                                </TouchableOpacity>
                            </LinearGradient>
                        </View>
                    </View>
                </View>
                <Indicator isVisible={this.state.indicatorVisable}/>
            </KeyboardAwareScrollView>
        );
    }
}

const styles = StyleSheet.create({
    bgCricle1: {
        width: 50, height: 50, position: 'absolute', borderRadius: 25, top: 29, right: 30
    },
    bgCricle2: {
        width: 20, height: 20, position: 'absolute', borderRadius: 10, top: 100, left: 5
    },
    bgCricle3: {
        width: 80, height: 80, position: 'absolute', borderRadius: 40, top: 200, left: -30
    },
    bgCricle4: {
        width: 20, height: 20, position: 'absolute', borderRadius: 40, top: 280, right: 20
    },
    bgCricle5: {
        width: 80, height: 80, position: 'absolute', borderRadius: 40, bottom: -40, right: 25
    },
    bgLogoImg: {
        width: 200, height: 210, marginTop: 20
    },
    submitBtn: {
        borderRadius: 20, width: 130, marginTop: 15
    }
});